﻿using System;
using System.Collections.ObjectModel;
using System.Net;
using System.Text;
using System.Windows;
using eLearning.Model;
using eLearning.Util;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Newtonsoft.Json;

namespace eLearning.View
{
    public partial class ThreadFormPage : PhoneApplicationPage
    {
        public ObservableCollection<DetailMatkul> perkuliahan;
        private bool firstLoaded;
        private Thread forum;

        public ThreadFormPage()
        {
            InitializeComponent();

            perkuliahan = new ObservableCollection<DetailMatkul>();

            if (SavedUser.Instance.User.Type == User.UserType.Dosen)
                GetListPerkuliahanDosen();
            else
                GetListPerkuliahanMahasiswa();

            this.Loaded += new RoutedEventHandler(DataContextPage_Loaded);
        }
        
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            if (e.NavigationMode == System.Windows.Navigation.NavigationMode.Back)
                firstLoaded = false;
            else
                firstLoaded = true;
        }

        private void DataContextPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (PhoneApplicationService.Current.State.ContainsKey(Config.THREAD))
            {
                forum = (Thread)PhoneApplicationService.Current.State[Config.THREAD];

                if (firstLoaded)
                {
                    if (forum != null && forum.Id != null)
                    {
                        //if (kuliahList.ItemsSource != null)
                        //    kuliahList.SelectedItem = forum.DetMatkul;
                        textBoxJudul.Text = forum.Judul;
                        textBoxIsiThread.Text = forum.Isi;
                    }
                    else
                    {
                        textBoxJudul.Text = "";
                        textBoxIsiThread.Text = "";
                    }
                }
            }
        }

        private void GetListPerkuliahanDosen()
        {
            kuliahList.ItemsSource = null;

            DetailMatkul kuliah = new DetailMatkul();
            kuliah.Creator = (Dosen)SavedUser.Instance.User.ConvertUser();
            string json = JsonConvert.SerializeObject(kuliah);

            WebClient webClient = new WebClient();

            string url = Config.Instance.PERKULIAHAN_SERVICE_URL() + Config.PERKULIAHAN_DOSEN_VIEW_KEY;
            Uri uri = new Uri(url, UriKind.Absolute); webClient.Encoding = Encoding.UTF8;
            webClient.Headers[HttpRequestHeader.ContentType] = "application/json";
            webClient.Headers[HttpRequestHeader.ContentLength] = json.Length.ToString();
            webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(listPerkuliahanDosen_UploadStringCompleted);
            webClient.UploadStringAsync(uri, "POST", json);
        }

        private void listPerkuliahanDosen_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            try
            {
                perkuliahan = JsonConvert.DeserializeObject<ObservableCollection<DetailMatkul>>(e.Result);
                kuliahList.ItemsSource = perkuliahan;
                if (forum != null && forum.DetMatkul != null)
                    kuliahList.SelectedItem = forum.DetMatkul;
            }
            catch (Exception ex)
            {
                MessageBox.Show("ERROR : " + ex.Message);
            }
        }

        private void GetListPerkuliahanMahasiswa()
        {
            Mahasiswa mahasiswa = (Mahasiswa)SavedUser.Instance.User.ConvertUser();
            string json = JsonConvert.SerializeObject(mahasiswa);

            string url = Config.Instance.PERKULIAHAN_SERVICE_URL() + Config.VIEW_JOINED_PERKULIAHAN_KEY;

            string urlformat = string.Format("{0}&{1}", url, Guid.NewGuid().ToString());
            Uri uri = new Uri(urlformat, UriKind.Absolute);

            WebClient webClient = new WebClient();
            webClient.Encoding = Encoding.UTF8;
            webClient.Headers[HttpRequestHeader.ContentType] = "application/json";
            webClient.Headers[HttpRequestHeader.ContentLength] = json.Length.ToString();
            webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(listMyPerkuliahanMhs_UploadStringCompleted);

            webClient.UploadStringAsync(uri, "POST", json);
        }

        private void listMyPerkuliahanMhs_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            try
            {
                PerkuliahanList list = JsonConvert.DeserializeObject<PerkuliahanList>(e.Result);

                kuliahList.ItemsSource = list;
                if (forum != null && forum.DetMatkul != null)
                    kuliahList.SelectedItem = forum.DetMatkul;
            }
            catch (Exception ex)
            {
                MessageBox.Show("ERROR : " + ex.Message);
            }
        }

        private void SaveThread(Thread data, bool add)
        {
            string json = null, url = null;

            if (add)
                url = Config.Instance.THREAD_SERVICE_URL() + Config.ADD_ACTION_KEY;
            else
                url = Config.Instance.THREAD_SERVICE_URL() + Config.UPDATE_ACTION_KEY;

            json = JsonConvert.SerializeObject(data);


            Uri uri = new Uri(url, UriKind.Absolute);
            WebClient client = new WebClient();

            client.Encoding = Encoding.UTF8;
            client.Headers[HttpRequestHeader.ContentType] = "application/json";
            client.Headers[HttpRequestHeader.ContentLength] = json.Length.ToString();

            client.UploadStringCompleted += new UploadStringCompletedEventHandler(createThread_UploadStringCompleted);

            try
            {
                client.UploadStringAsync(uri, "POST", json);
            }
            catch (Exception) { }
        }

        private void createThread_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            try
            {
                if (e.Cancelled || e.Error != null)
                    return;

                MessageBox.Show("Message : " + e.Result);

                if (e.Result.Contains("Success"))
                    NavigationService.GoBack();
            }
            catch (Exception ex)
            {
                MessageBox.Show("ERROR : " + ex.Message);
            }
        }

        private void buttonSave_Click(object sender, System.EventArgs e)
        {
            if (forum == null)
                forum = new Thread();

            forum.Judul = textBoxJudul.Text;
            forum.Isi = textBoxIsiThread.Text;
            forum.Creator = SavedUser.Instance.User;
            DetailMatkul detMatkul = ((DetailMatkul)kuliahList.SelectedItem);
            forum.DetMatkul = detMatkul;

            SaveThread(forum, forum.Id == null);
        }

        private void buttonCancel_Click(object sender, System.EventArgs e)
        {
            NavigationService.GoBack();
        }

    }
}